package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import common.Constant;
import dao.MonHocDAO;
import dao.SinhVienDAO;
import dao.ThanhVienDAO;
import dao.DangKyDAO;
import model.MonHocModel;
import model.SinhVienModel;
import model.ThanhVienModel;
import model.DangKyModel;
import util.DataUtil;
import util.LogUtil;
import util.StringUtil;

public class ThanhVienController extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(DataUtil.class.getName());
	private static final Logger loggerInfo = Logger.getLogger("LogINFO");
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String actionType = request.getParameter("actionType").toString();
		
		
		if(actionType.equalsIgnoreCase("login")){// login goi
			doPostLogin(request, response);
		}
		//danh sach sinh vien
		else if(actionType.equalsIgnoreCase("capnhatsinhvien")){
			updateSinhVienByMaSV(request, response);
		}
		else if(actionType.equalsIgnoreCase("themmoisinhvien")){
			insertSinhVien(request, response);
		}
		else if(actionType.equalsIgnoreCase("sinhVien"))
		{
			SinhVien(request,response);
		}
		else if(actionType.equalsIgnoreCase("DangKyMonHoc"))
		{
			DangKyMonHoc(request,response);
		}
		//danh sach mon hoc
		else if(actionType.equalsIgnoreCase("capnhatmonhoc")){
			updateMonHocByMaMH(request, response);
		}
		else if(actionType.equalsIgnoreCase("themmoimonhoc")){
			insertMonHoc(request, response);
		}
		else if(actionType.equalsIgnoreCase("monHoc"))
		{
			MonHoc(request,response);
		}
		else if(actionType.equalsIgnoreCase("DangKySinhVien")){
			DangKySinhVien(request, response);
		}
	}
	
	private void doPostLogin (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String tenDangNhap = request.getParameter("txtTenDangNhap");
		String matKhau = request.getParameter("txtMatKhau");
		
		HttpSession session = request.getSession(true);
		
		if(tenDangNhap != "" && matKhau != ""){
			//ThanhVienModel chiTietthanhVienModel = ThanhVienDAO.timChiTietThanhVien(tenDangNhap);
			
				ThanhVienModel thanhVienModel = ThanhVienDAO.timThanhVien(tenDangNhap, matKhau);
				if(thanhVienModel != null){
					if (thanhVienModel.getTenDangNhap().equals(tenDangNhap)) { // ten dang nhap dung
						if(thanhVienModel.getMatKhau().equals(matKhau)){//Dang nhap thanh cong
							//if(chiTietthanhVienModel.getTinhTrang().equals("1")){
								//bao cao da dang nhap thanh cong
							session.setAttribute(Constant.USERID_ATT, thanhVienModel.getMaThanhVien());
							session.setAttribute(Constant.USERNAME_ATT, thanhVienModel.getTenDangNhap());
							session.setAttribute(Constant.PASSWORD_ATT, thanhVienModel.getMatKhau());
							
								LogUtil.logInfo(loggerInfo, "Thanh Vien Dang Nhap la : " 
															+ thanhVienModel.getTenDangNhap() 
															+ " Da dang nhap thanh cong");
								}
								String pageNext = "home.jsp";
								response.sendRedirect(pageNext);
							}else{//sai mat khau
								response.sendRedirect("login.jsp"
										+ "?err=" + "err");
						}
						
					} else { // sai ten dang nhap
						response.sendRedirect("login.jsp"
								+ "?err=" + "err");
					}
				}else{//Dang nhap that bai
					response.sendRedirect("login.jsp"
							+ "?err=" + "err");
				}
	}
	
	//danh sach sinh vien
	
	private void updateSinhVienByMaSV(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		SinhVienModel sinhVienModel=new SinhVienModel();
		sinhVienModel.setMaSV(request.getParameter("txtMaSinhVien").trim());
		sinhVienModel.setTenSV(StringUtil.toUTF8(request.getParameter("txtTenSinhVien").trim()));
		sinhVienModel.setNgaySinh(request.getParameter("txtNgaySinh").trim());
		sinhVienModel.setGioiTinh(request.getParameter("txtGioiTinh").trim());
		sinhVienModel.setDiaChi(StringUtil.toUTF8(request.getParameter("txtDiaChi").trim()));
				
		if(SinhVienDAO.updateSinhVienByMaSV(sinhVienModel))
			response.sendRedirect("sinhvien/danhsachsinhvien.jsp?errUpdate=false"+request.getParameter("txtProLink"));
		else
			response.sendRedirect("sinhvien/danhsachsinhvien.jsp?errUpdate=true"+request.getParameter("txtProLink"));
			
	}
	
	private void insertSinhVien(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		SinhVienModel sinhVienModel=new SinhVienModel();
		sinhVienModel.setMaSV(request.getParameter("txtMaSinhVien").trim());
		sinhVienModel.setTenSV(StringUtil.toUTF8(request.getParameter("txtTenSinhVien").trim()));
		sinhVienModel.setNgaySinh(request.getParameter("selThang") + "/" + request.getParameter("selNgay") + "/" + request.getParameter("selNam"));
		sinhVienModel.setGioiTinh(request.getParameter("txtGioiTinh").trim());
		sinhVienModel.setDiaChi(StringUtil.toUTF8(request.getParameter("txtDiaChi").trim()));
		
		if(SinhVienDAO.insertSinhVien(sinhVienModel))
			response.sendRedirect("sinhvien/danhsachsinhvien.jsp?errInsert=false"+request.getParameter("txtProLink"));
		else
			response.sendRedirect("sinhvien/danhsachsinhvien.jsp?errInsert=true"+request.getParameter("txtProLink"));
	}
	
	protected void SinhVien(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String maSinhVien = "";
		String pageNext = "sinhvien/danhsachsinhvien.jsp?MaSinhVien=" + maSinhVien ;
		RequestDispatcher rd = request.getRequestDispatcher(pageNext);	
		
		ArrayList<SinhVienModel> sinhVienModelList1  = new ArrayList<SinhVienModel>();
		ArrayList<SinhVienModel> sinhVienModelList2  = new ArrayList<SinhVienModel>();
		if(request.getSession().getAttribute("sinhVienList") != null)
			sinhVienModelList1 = (ArrayList<SinhVienModel>)request.getSession().getAttribute("sinhVienList");
		
		for(Integer i = 1; i <= sinhVienModelList1.size(); i++){
			
			SinhVienModel sinhVienModel = sinhVienModelList1.get(i-1);
			
			if(request.getParameter("xoaSV") != null && request.getParameter("xoaSV").equals("xoa") && request.getParameter("chk" + i.toString()) != null)
			{
				if(sinhVienModel.getMaSV() != null){
					SinhVienDAO.deleteSinhVien(sinhVienModel.getMaSV());
				}
			}
			else{
				sinhVienModelList2.add(sinhVienModel);
			}
		}
		
		if(request.getParameter("xoaSV").equals("xoa"))
		{
			
			rd = request.getRequestDispatcher(pageNext);	
			pageNext += "?xoa=DeleteTC";
		}
		request.setAttribute(Constant.SINH_VIEN_MODEL_LIST, sinhVienModelList2);
		rd.forward(request, response);
	}
	
	private void DangKyMonHoc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String actionStatus = StringUtil.toUTF8(request.getParameter("actionStatus"));
		
		if(actionStatus.equalsIgnoreCase("them"))
		{
			String[] maMonHoc=request.getParameterValues("cboChuaDangKy");
			
			DangKyModel dangKyModel;
			for(int i=0;i<maMonHoc.length;i++){
				dangKyModel=new DangKyModel();
				dangKyModel.setMaMH(maMonHoc[i]);
				dangKyModel.setMaSV(request.getParameter("maSinhVien"));
				if(DangKyDAO.insertMonHocDangKy(dangKyModel)==false){					
					response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=insertTB&maSinhVien="+request.getParameter("maSinhVien"));
				}
			}
				response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=insertTC&maSinhVien="+request.getParameter("maSinhVien"));
		}
		
		else if(actionStatus.equalsIgnoreCase("huyAll")){
			String maSinhVien=request.getParameter("maSinhVien");
			ArrayList<MonHocModel> monHocModel = DangKyDAO.getMonHocDaDangKy(maSinhVien);
			int i=0;
			while(i<monHocModel.size())
			{
				if(DangKyDAO.deleteMonHocDangKy(monHocModel.get(i).getMaMH(),maSinhVien)==false)
					response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=deleteTB&maSinhVien="+request.getParameter("maSinhVien"));				
					
				i++;
			}
			response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=deleteTC&maSinhVien="+request.getParameter("maSinhVien"));					
	
		}
		else if(actionStatus.equalsIgnoreCase("themAll")){
			String maSinhVien=request.getParameter("maSinhVien");
			ArrayList<MonHocModel> monHocModel = DangKyDAO.getMonHocChuaDangKy(maSinhVien);
			int i=0;
			DangKyModel dangKyModel;
			
			while(i<monHocModel.size())
			{
				dangKyModel=new DangKyModel();
				dangKyModel.setMaMH(monHocModel.get(i).getMaMH());
				dangKyModel.setMaSV(request.getParameter("maSinhVien"));
			
				if(DangKyDAO.insertMonHocDangKy(dangKyModel)==false)
					response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=insertTB&maSinhVien="+request.getParameter("maSinhVien"));					
				i++;
			}
			response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=insertTC&maSinhVien="+request.getParameter("maSinhVien"));					
	
		}
		else
		{
			String[] maMonHoc=request.getParameterValues("cboDangKy");
			
			for(int i=0;i<maMonHoc.length;i++){
				if(DangKyDAO.deleteMonHocDangKy(maMonHoc[i],request.getParameter("maSinhVien"))==false){
					response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=deleteTB&maSinhVien="+request.getParameter("maSinhVien"));					
				}
			}
				response.sendRedirect("sinhvien/chitietsinhvien.jsp?err=deleteTC&maSinhVien="+request.getParameter("maSinhVien"));
		}
	}
	
	//danh sach mon hoc
	
	private void updateMonHocByMaMH(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		MonHocModel monHocModel=new MonHocModel();
		monHocModel.setMaMH(request.getParameter("txtMaMonHoc").trim());
		monHocModel.setTenMH(StringUtil.toUTF8(request.getParameter("txtTenMonHoc").trim()));
		monHocModel.setThoiGianBatDau(request.getParameter("txtThoiGianBatDau").trim());
		monHocModel.setThoiGianKetThuc(request.getParameter("txtThoiGianKetThuc").trim());
		monHocModel.setChungChi(request.getParameter("txtChungChi").trim());
		monHocModel.setLePhi(request.getParameter("txtLePhi").trim());
				
		if(MonHocDAO.updateMonHocByMaMH(monHocModel))
			response.sendRedirect("monhoc/danhsachmonhoc.jsp?errUpdate=false"+request.getParameter("txtProLink"));
		else
			response.sendRedirect("monhoc/danhsachmonhoc.jsp?errUpdate=true"+request.getParameter("txtProLink"));
			
	}
	
	private void insertMonHoc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		MonHocModel monHocModel=new MonHocModel();
		monHocModel.setMaMH(request.getParameter("txtMaMonHoc").trim());
		monHocModel.setTenMH(StringUtil.toUTF8(request.getParameter("txtTenMonHoc").trim()));		
		monHocModel.setThoiGianBatDau(request.getParameter("selThangBatDau")+ "/" + request.getParameter("selNgayBatDau") + "/" + request.getParameter("selNamBatDau"));
		monHocModel.setThoiGianKetThuc(request.getParameter("selThangKetThuc")+ "/" + request.getParameter("selNgayKetThuc") + "/" + request.getParameter("selNamKetThuc"));
		monHocModel.setChungChi(request.getParameter("txtChungChi").trim());
		monHocModel.setLePhi(request.getParameter("txtLePhi").trim());
		
		if(MonHocDAO.insertMonHoc(monHocModel))
			response.sendRedirect("monhoc/danhsachmonhoc.jsp?errInsert=false"+request.getParameter("txtProLink"));
		else
			response.sendRedirect("monhoc/danhsachmonhoc.jsp?errInsert=true"+request.getParameter("txtProLink"));
			
	}
	
	protected void MonHoc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String maMonHoc = "";
		String pageNext = "monhoc/danhsachmonhoc.jsp?MaMonHoc=" + maMonHoc ;
		RequestDispatcher rd = request.getRequestDispatcher(pageNext);	
		
		ArrayList<MonHocModel> monHocModelList1  = new ArrayList<MonHocModel>();
		ArrayList<MonHocModel> monHocModelList2  = new ArrayList<MonHocModel>();
		if(request.getSession().getAttribute("monHocList") != null)
			monHocModelList1 = (ArrayList<MonHocModel>)request.getSession().getAttribute("monHocList");
		
		for(Integer i = 1; i <= monHocModelList1.size(); i++){
			
			MonHocModel monHocModel = monHocModelList1.get(i-1);
			
			if(request.getParameter("xoaMH") != null && request.getParameter("xoaMH").equals("xoa") && request.getParameter("chk" + i.toString()) != null)
			{
				if(monHocModel.getMaMH() != null){
					MonHocDAO.deleteMonHoc(monHocModel.getMaMH());
				}
			}
			else{
				monHocModelList2.add(monHocModel);
			}
		}
		
		if(request.getParameter("xoaMH").equals("xoa"))
		{
			
			rd = request.getRequestDispatcher(pageNext);	
			pageNext += "?xoa=DeleteTC";
		}
		request.setAttribute(Constant.MON_HOC_MODEL_LIST, monHocModelList2);
		rd.forward(request, response);
	}
	
	private void DangKySinhVien(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String actionStatus = StringUtil.toUTF8(request.getParameter("actionStatus"));
		
		if(actionStatus.equalsIgnoreCase("them"))
		{
			String[] maSinhVien=request.getParameterValues("cboChuaDangKy");
			
			DangKyModel dangKyModel;
			for(int i=0;i<maSinhVien.length;i++){
				dangKyModel=new DangKyModel();
				dangKyModel.setMaSV(maSinhVien[i]);
				dangKyModel.setMaMH(request.getParameter("maMonHoc"));
				if(DangKyDAO.insertSinhVienDangKy(dangKyModel)==false){					
					response.sendRedirect("monhoc/chitietmonhoc.jsp?err=insertTB&maMonHoc="+request.getParameter("maMonHoc"));
				}
			}
				response.sendRedirect("monhoc/chitietmonhoc.jsp?err=insertTC&maMonHoc="+request.getParameter("maMonHoc"));
		}
		
		else if(actionStatus.equalsIgnoreCase("huyAll")){
			String maMonHoc=request.getParameter("maMonHoc");
			ArrayList<SinhVienModel> sinhVienModel = DangKyDAO.getSinhVienDaDangKy(maMonHoc);
			int i=0;
			while(i<sinhVienModel.size())
			{
				if(DangKyDAO.deleteSinhVienDangKy(sinhVienModel.get(i).getMaSV(),maMonHoc)==false)
					response.sendRedirect("monhoc/chitietmonhoc.jsp?err=deleteTB&maMonHoc="+request.getParameter("maMonHoc"));				
					
				i++;
			}
			response.sendRedirect("monhoc/chitietmonhoc.jsp?err=deleteTC&maMonHoc="+request.getParameter("maMonHoc"));					
	
		}
		else if(actionStatus.equalsIgnoreCase("themAll")){
			String maMonHoc=request.getParameter("maMonHoc");
			ArrayList<SinhVienModel> sinhVienModel = DangKyDAO.getSinhVienChuaDangKy(maMonHoc);
			int i=0;
			DangKyModel dangKyModel;
			
			while(i<sinhVienModel.size())
			{
				dangKyModel=new DangKyModel();
				dangKyModel.setMaSV(sinhVienModel.get(i).getMaSV());
				dangKyModel.setMaMH(request.getParameter("maMonHoc"));
			
				if(DangKyDAO.insertSinhVienDangKy(dangKyModel)==false)
					response.sendRedirect("monhoc/chitietmonhoc.jsp?err=insertTB&maMonHoc="+request.getParameter("maMonHoc"));					
					
				i++;
			}
			response.sendRedirect("monhoc/chitietmonhoc.jsp?err=insertTC&maMonHoc="+request.getParameter("maMonHoc"));					
	
		}
		else
		{
			String[] maSinhVien=request.getParameterValues("cboDangKy");
			
			for(int i=0;i<maSinhVien.length;i++){
				if(DangKyDAO.deleteSinhVienDangKy(maSinhVien[i],request.getParameter("maMonHoc"))==false){
					response.sendRedirect("monhoc/chitietmonhoc.jsp?err=deleteTB&maMonHoc="+request.getParameter("maMonHoc"));					
				}
			}
				response.sendRedirect("monhoc/chitietmonhoc.jsp?err=deleteTC&maMonHoc="+request.getParameter("maMonHoc"));
		}
	}
}